#include "Channel.h"
#include <sys/epoll.h>
#include "EventLoop.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include "util.h"
#include <poll.h>

Channel::Channel(EventLoop* loop, int fd) 
    : loop_(loop), 
    fd_(fd),
    events_(0),
    revents_(0),
    index_(0),
    eventHandling_(false),
    isDesturct_(false)
{
}

Channel::~Channel() {
}

void Channel::update() {
    loop_->updateChannel(this);
}

void Channel::remove() {
    assert(isNoneEvent());
    loop_->removeChannel(this);
}

void Channel::handleEvent() {
    eventHandling_ = true;
    if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
        if (closeCallback_) closeCallback_();
    }
    if (revents_ & (EPOLLERR)) {
        if (errorCallback_) errorCallback_();
    }
    if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
        if (readCallback_) readCallback_();
    }
    if (revents_ & EPOLLOUT) {
        if (writeCallback_) writeCallback_();
    }
    eventHandling_ = false;
}